package com.java110.mall.shop.cmd.shop;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.store.StoreDto;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.IStoreV1InnerServiceSMO;
import com.java110.po.shop.ShopPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Java110Cmd(serviceCode = "shop.deleteShop")
public class DeleteShopCmd extends Cmd {

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IStoreV1InnerServiceSMO storeInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

        Assert.hasKeyAndValue(reqJson, "shopId", "商铺ID不存在");

        String storeId = cmdDataFlowContext.getReqHeaders().get("store-id");

        StoreDto storeDto = new StoreDto();
        storeDto.setStoreId(storeId);
        List<StoreDto> storeDtos = storeInnerServiceSMOImpl.queryStores(storeDto);
        Assert.listOnlyOne(storeDtos, "商户不存在");

        if (StoreDto.STORE_TYPE_ADMIN.equals(storeDtos.get(0).getStoreTypeCd())) { // 运营可以删除
            return;
        }

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(reqJson.getString("shopId"));
        shopDto.setStoreId(storeId);
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        Assert.listOnlyOne(shopDtos, "店铺不存在");

    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        ShopPo shopPo = new ShopPo();
        shopPo.setShopId(reqJson.getString("shopId"));
        int flag = shopInnerServiceSMOImpl.deleteShop(shopPo);

        if (flag < 1) {
            throw new CmdException("删除店铺失败");
        }

    }
}
